package dfbz.com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 拦截未经登录访问网页资源(html里的)的所有请求
 */
@WebFilter(urlPatterns = {"/html/*"}, dispatcherTypes = {DispatcherType.FORWARD, DispatcherType.REQUEST})
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Object userIfoId = req.getSession().getAttribute("userId");
        boolean flag = false;
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userName".equals(cookie.getName())) {
                   // System.out.println("拿到了记住我的cookie");
                    flag = true;
                    break;
                }
            }
        }
        //如果登录成功或者记住我没有失效，就直接放行，可以直接访问资源
        if (flag||null!=userIfoId){
            filterChain.doFilter(req,resp);
        } else{
            //没有经过登录,返回登录界面
            System.out.println("没有userId，返回登录界面");
            resp.sendRedirect("/");
        }
    }

    @Override
    public void destroy() {

    }
}
